package com.junzhiit.nengji.cms.service.impl;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.bainaeco.framework.util.DateUtil;
import com.bainaeco.framework.util.JsonUtil;
import com.junzhiit.nengji.bo.FlowSessionCntBO;
import com.junzhiit.nengji.bo.FlowStayTimeSessionBO;
import com.junzhiit.nengji.bo.FlowStayTimeUvBO;
import com.junzhiit.nengji.bo.FlowVisitPvBO;
import com.junzhiit.nengji.bo.FlowVisitUvBO;
import com.junzhiit.nengji.bo.FlowVisitUvNewBO;
import com.junzhiit.nengji.cms.service.WechatFlowHistoryService;
import com.junzhiit.nengji.cms.web.util.Constants;
import com.junzhiit.nengji.cms.web.util.wechat.WeChatUtils;
import com.junzhiit.nengji.cms.web.util.wechat.bean.AccessToken;
import com.junzhiit.nengji.cms.web.vo.ResultVO;
import com.junzhiit.nengji.cms.web.vo.WechatFlowHistoryVO;
import com.junzhiit.nengji.dao.WechatFlowHistoryDAO;
import com.junzhiit.nengji.model.WechatFlowHistory;

@Service
public class WechatFlowHistoryServiceImpl extends BaseServiceImpl  implements WechatFlowHistoryService{
	
	@Autowired
	private WechatFlowHistoryDAO wechatFlowHistoryDAO;
	
	@SuppressWarnings("unchecked")
	@Override
	public void flowHistory(){
		WechatFlowHistory flowHistory=new WechatFlowHistory();
		AccessToken accessToken = WeChatUtils.getAccessToken();
		Map<String, String> params = new HashMap<String,String>();
		Map<String, Object> map = new HashMap<>();
		Date newDate = DateUtil.getDate(new Date(),-1);
		params.put("begin_date", DateUtil.format(DateUtil.getDateStart(newDate),DateUtil.DATE_PATTERN_YYYYMMDD));
		params.put("end_date", DateUtil.format(DateUtil.getDateEnd(newDate),DateUtil.DATE_PATTERN_YYYYMMDD));
		
		CloseableHttpClient  httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(Constants.URL_FLOW_HISTORY+accessToken.getAccessToken());  // 接口
        httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
        String body = JsonUtil.toJson(params); //必须是json模式的 post
        StringEntity entity;
        
        try {
			entity = new StringEntity(body,"UTF-8");
			entity.setContentEncoding("UTF-8");
			entity.setContentType("application/json");
	        httpPost.setEntity(entity);
	        CloseableHttpResponse response;

	        response =  httpClient.execute(httpPost);
	        
	        //请求发送成功，并得到相应
	        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                String str = "";
                try{
                    // 读取服务器返回过来的json字符串数据
                    str = EntityUtils.toString(response.getEntity(), "utf-8");
                    // 把json字符串转换成json对象
                    map=JsonUtil.toMap(str);
                }
                catch (Exception e){
                    logger.error("post请求提交失败:" + Constants.URL_FLOW_HISTORY, e);
                }
            }
	        if (map.get("list") != null) {
	        	List<Object> list=(ArrayList<Object>)map.get("list");
	        	if(!list.isEmpty()){
		        	Map<String,Object> maps=JsonUtil.toMap(list.get(0));
		        	flowHistory.setRefDate(DateUtil.parseDate(DateUtil.DATE_PATTERN_YYYYMMDD,maps.get("ref_date").toString()));
		        	flowHistory.setSessionCnt((Integer)maps.get("session_cnt"));
		        	flowHistory.setVisitPv((Integer)maps.get("visit_pv"));
		        	flowHistory.setVisitUv((Integer)maps.get("visit_uv"));
		        	flowHistory.setVisitUvNew((Integer)maps.get("visit_uv_new"));
		        	flowHistory.setStayTimeUv((Double)maps.get("stay_time_uv"));
		        	flowHistory.setStayTimeSession((Double)maps.get("stay_time_session"));
	        	}
			}
	        wechatFlowHistoryDAO.insert(flowHistory);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public ResultVO queryFlowInfo(Integer year, Integer month) {
		//初始化存放数据的集合
		ResultVO result=new ResultVO();
		List<String> item=new ArrayList<String>();
		List<Integer> sessionCnt = new ArrayList<Integer>();
		List<Integer> visitPv = new ArrayList<Integer>();
		List<Integer> visitUv = new ArrayList<Integer>();
		List<Integer> visitUvNew = new ArrayList<Integer>();
		List<Double> stayTimeUv = new ArrayList<Double>();
		List<Double> stayTimeSession = new ArrayList<Double>();
		
		if(year==null||month==null){
			return result;
		}
		
		Calendar cl=Calendar.getInstance();
		cl.set(Calendar.MONTH,month-1);
		int daysCount=cl.getActualMaximum(Calendar.DATE);
		
//		Date date=DateUtil.getCurrentDate();
//		int nowYear=DateUtil.getYear(date);
//		int nowMonth=DateUtil.getMonth(date);
//		
//		int nowDay=DateUtil.getDayOfMonth((DateUtil.getDate(date, -1)));
//		
//		daysCount=((nowYear==year.intValue())&&((nowMonth+1)==month.intValue()))?nowDay:daysCount;
		
		//存放小程序打开的次数
		List<FlowSessionCntBO> fsb=wechatFlowHistoryDAO.querySessionCnt(year, month);
		Map<Integer, FlowSessionCntBO>  fsbmaps= fsb.stream().collect(Collectors.toMap(FlowSessionCntBO::getDay, FlowSessionCntBO -> FlowSessionCntBO));
		
		//存放小程序访问的次数
		List<FlowVisitPvBO> fvp=wechatFlowHistoryDAO.queryFlowVisitPv(year, month);
		Map<Integer, FlowVisitPvBO> fvpmaps=fvp.stream().collect(Collectors.toMap(FlowVisitPvBO::getDay, FlowVisitPvBO -> FlowVisitPvBO));
		
		//存放小程序访问的人数
		List<FlowVisitUvBO> fvu=wechatFlowHistoryDAO.queryFlowVisitUv(year, month);
		Map<Integer, FlowVisitUvBO> fvumaps=fvu.stream().collect(Collectors.toMap(FlowVisitUvBO::getDay, FlowVisitUvBO -> FlowVisitUvBO));
		
		//存放小程序新用户数
		List<FlowVisitUvNewBO> fvun=wechatFlowHistoryDAO.queryFlowVisitUvNew(year, month);
		Map<Integer, FlowVisitUvNewBO> fvunmaps=fvun.stream().collect(Collectors.toMap(FlowVisitUvNewBO::getDay, FlowVisitUvNewBO -> FlowVisitUvNewBO));
		
		//存放小程序人均停留时间
		List<FlowStayTimeUvBO> fstu=wechatFlowHistoryDAO.queryFlowStayTimeUv(year, month);
		Map<Integer, FlowStayTimeUvBO> fstumaps=fstu.stream().collect(Collectors.toMap(FlowStayTimeUvBO::getDay, FlowStayTimeUvBO -> FlowStayTimeUvBO));
		
		//存放小程序次均停留时间
		List<FlowStayTimeSessionBO> fsts=wechatFlowHistoryDAO.queryFlowStayTimeSession(year, month);
		Map<Integer, FlowStayTimeSessionBO> fstsmaps=fsts.stream().collect(Collectors.toMap(FlowStayTimeSessionBO::getDay, FlowStayTimeSessionBO -> FlowStayTimeSessionBO));
		
		String prefixStr=String.valueOf(year)+"-"+String.valueOf(month)+"-";
		for(int i=1;i<=daysCount;i++){
			item.add(prefixStr+String.valueOf(i));
			if(fsbmaps.containsKey(i)){
				sessionCnt.add(fsbmaps.get(i).getSessionCnt());
			}else{
				sessionCnt.add(0);
			}
			
			if(fvpmaps.containsKey(i)){
				visitPv.add(fvpmaps.get(i).getVisitPv());
			}else{
				visitPv.add(0);
			}
			
			if(fvumaps.containsKey(i)){
				visitUv.add(fvumaps.get(i).getVisitUv());
			}else{
				visitUv.add(0);
			}
			
			if(fvunmaps.containsKey(i)){
				visitUvNew.add(fvunmaps.get(i).getVisitUvNew());
			}else{
				visitUvNew.add(0);
			}
			
			if(fstumaps.containsKey(i)){
				stayTimeUv.add(fstumaps.get(i).getStayTimeUv());
			}else{
				stayTimeUv.add(0.00);
			}
			
			if(fstsmaps.containsKey(i)){
				stayTimeSession.add(fstsmaps.get(i).getStayTimeSession());
			}else{
				stayTimeSession.add(0.00);
			}
		}
		
		WechatFlowHistoryVO wechatFlowHistoryVO=new WechatFlowHistoryVO();
		
		List<Object> data=new ArrayList<Object>();
		data.add(sessionCnt);
		data.add(visitPv);
		data.add(visitUv);
		data.add(visitUvNew);
		data.add(stayTimeUv);
		data.add(stayTimeSession);
		
		wechatFlowHistoryVO.setData(data);
		wechatFlowHistoryVO.setItem(item);
		
		result.setData(wechatFlowHistoryVO);
		
		return result;
	}
}
